<template>
  <d2-container>
    <div class="search">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList(true)" size="small">
        <el-form-item>
          <el-input v-model="dataForm.planName" placeholder="计划名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请选择计量器"
                    class="filter-item" clearable
                    style="width:280px;"
                    ref="meterObj"
                    @click.native="handleClick"
                    v-model="dataForm.meterCodeName">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="dataForm.status" placeholder="巡检状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划巡检时间" label-width="120px">
          <el-date-picker
            v-model="dataForm.date"
            placeholder="时间范围"
            style="width: 350px;"
            class="filter-item"
            :picker-options="pickerOptions"
            type="daterange"
            suffix-icon="el-icon-date"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button @click="sizeChangeHandle(10)">查询</el-button>
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-download"
            size="mini"
            @click="exoprtData"
          >导出</el-button>
        </el-form-item>
      </el-form>
    </div>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        style="width: 100%;">
        <el-table-column
          prop="planName"
          header-align="center"
          align="center"
          label="计划名称">
        </el-table-column>
        <el-table-column
          prop="planContent"
          header-align="center"
          align="center"
          label="计划内容">
        </el-table-column>
        <el-table-column
          prop="meterCode"
          header-align="center"
          align="center"
          label="计量器">
          <template slot-scope="scope">
            {{scope.row.meterCode |meterName(meterList)}}
          </template>
        </el-table-column>
        <el-table-column
          prop="planCycle"
          header-align="center"
          align="center"
          label="巡检周期">
          <template slot-scope="scope">
            {{scope.row.planCycle |dateName(dateTypeList)}}
          </template>
        </el-table-column>
        <el-table-column
          prop="planPatrolTime"
          header-align="center"
          align="center"
          label="计划巡检时间">
        </el-table-column>
        <el-table-column
          prop="patrolTime"
          header-align="center"
          align="center" min-width="140"
          label="实际巡检时间">
        </el-table-column>
        <el-table-column
          prop="status"
          header-align="center"
          align="center"
          label="巡检状态">
          <template slot-scope="scope">
            {{scope.row.status |stateName(statusOptions)}}
          </template>
        </el-table-column>
        <el-table-column
          prop="patrolUserId"
          header-align="center"
          align="center"
          label="巡检人">
          <template slot-scope="scope">
            {{scope.row.patrolUserId |userName(userList)}}
          </template>
        </el-table-column>
        <!--<el-table-column-->
          <!--prop="createTime"-->
          <!--header-align="center"-->
          <!--align="center"-->
          <!--label="创建时间">-->
        <!--</el-table-column>-->
        <el-table-column
          prop="updateTime"
          header-align="center"
          align="center"
          label="更新时间">
        </el-table-column>
        <el-table-column
          prop="remark"
          header-align="center"
          align="center"
          label="备注">
        </el-table-column>
        <!--<el-table-column-->
          <!--header-align="center"-->
          <!--align="center"-->
          <!--width="150"-->
          <!--label="操作">-->
          <!--<template slot-scope="scope">-->
            <!--<el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.planId)">修改</el-button>-->
            <!--<el-button type="text" size="small" @click="deleteHandle(scope.row.planId)">删除</el-button>-->
          <!--</template>-->
        <!--</el-table-column>-->
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <el-dialog title="选择计量器" :visible.sync="showTree">
      <el-tree
        :style="'height:'+(containerHeight-100)+'px'"
        ref="buildTree"
        highlight-current
        node-key="id"
        :data="treeDataList"
        :expand-on-click-node="false"
        :props="menuListTreeProps"
        @node-click="selectBuild"
        default-expand-all
      >
        <span class="custom-tree-node"  slot-scope="{ node, data }">
          <span :dataType="data.type">
              <!-- <i class="el-icon-setting"  v-if="data.type=='b'"></i> -->
              <i class="el-icon-star-off"  v-if="data.type=='d'"></i>
              {{ node.label }}
          </span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showTree = false">取 消</el-button>
      </div>
    </el-dialog>
  </d2-container>
</template>

<script>
  import AddOrUpdate from './patrolplan-add-or-update'
  import * as Util from "@/utils";
  export default {
    data () {
      return {
        dataForm: {
          planName: '',
          meterCodeName:'',
          meterCode: '',
          date:'',
          status:''
        },
        treeDataList:[],
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          }
        },
        statusOptions : [{"id":'0',"name":'未巡检'},{"id":'1',"name":'正常已巡检'},{"id":'2',"name":'上报缺陷'}],
        showTree: false,
        meterList: [],
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        meterTypeList:[],
        collectTypeList:[],
        dateTypeList:[{"key":"1","value":"日"},{"key":"2","value":"周"},{"key":"3","value":"月"}],
        userList: [],
        menuListTreeProps: {
          label: "name",
          children: "children"
        },
      }
    },
    components: {
      AddOrUpdate
    },
    filters: {
      dateName: function (value,statusList) {
        for(let i=0;i<statusList.length;i++){
          if(statusList[i].key===value){
            return statusList[i].value;
          }
        }
      },
      userName: function (value,statusList) {
        for(let i=0;i<statusList.length;i++){
          if(statusList[i].userId===value){
            return statusList[i].username;
          }
        }
      },
      meterName: function (value,statusList) {
        for(let i=0;i<statusList.length;i++){
          if(statusList[i].id===value){
            return statusList[i].name;
          }
        }
      },
      meterTypeName: function (value,statusList) {
        for(let i=0;i<statusList.length;i++){
          if(statusList[i].paramKey===value){
            return statusList[i].paramValue;
          }
        }
      },
      stateName: function (value,statusList) {
        for(let i=0;i<statusList.length;i++){
          if(statusList[i].id===value){
            return statusList[i].name;
          }
        }
      }
    },
    mounted () {
      this.getBuildDeviceList()
      this.queryUser()
      this.$nextTick(() => {this.getDataList()})
    },
    computed:{
      containerHeight() {
        return Util.getClientHeight() - 243;
      }
    },
    methods: {
      handleClick(event) {
        // 检查事件target是否不是清除按钮
        if (event.target.tagName != "INPUT") return;
         this.showTree = true
      },
      selectBuild(data){
        //console.log(data);
        //if(data.type=='m'){
        if(data.type=='d'){
          this.dataForm.meterCodeName = data.name;
          this.dataForm.meterCode = data.id;
          this.showTree = false;
        }
      },
      getBuildDeviceList(){
        //建筑-计量器树
        this.$api.okhttp({
          url: this.$http.adornUrl("/ecs/ecsbuildinginfo/getDeviceTree"),
          method: "get",
          params: this.$http.adornParams({
            'projectId': this.$util.cookies.get("cuuren_projectId"),
            "customerId":this.$util.cookies.get('customer_id')
          })
        }).then((res)=>{
          if (res && res.code == 0) {
            this.treeDataList = Util.treeDataTranslate(res.data,"id","pid");
            this.meterList = res.data
          }
        })
      },
      queryUser(){
          this.$api.okhttp({
          url: this.$http.adornUrl('/sys/user/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 1000,
            "customerId":this.$util.cookies.get('customer_id')
          })
        }).then((data) => {
          if (data && data.code === 0) {
            this.userList = data.page.list
          } else {
            this.userList = []
          }
        })
      },
      /**
       * 获取参数枚举
       */
      queryStatic(type,paramValue,callback) {
        let params = {
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        }
        if(paramValue){
          Object.assign(params,{...paramValue});
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        let startDate = ''
        let endDate = ''
        if(this.dataForm.date&&this.dataForm.date!==''){
          startDate = this.dataForm.date[0].format('yyyy-MM-dd')
          endDate = this.dataForm.date[1].format('yyyy-MM-dd')
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecspatrolplanrecord/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'planName': this.dataForm.planName,
            'meterCode': this.dataForm.meterCodeName !=''?this.dataForm.meterCode:'',
            'startDate': startDate,
            'endDate': endDate,
            'status': this.dataForm.status,
            'projectId': this.$util.cookies.get("cuuren_projectId"),
            "customerId":this.$util.cookies.get('customer_id')
          })
        }).then((data) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id,this.userList,this.treeDataList,this.meterList)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.planId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.okhttp({
            url: this.$http.adornUrl('/ecs/ecspatrolplan/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then((data) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      exoprtData(){
        let header=['计划名称','计划内容','计量器','巡检周期','计划巡检时间','实际巡检时间','巡检状态','巡检人','备注'];
        let props=['planName','planContent','meterCode','planCycle','planPatrolTime','patrolTime','status','patrolUserId','remark'];
        let fileName=`巡检记录`;
        let data = []
        this.dataList.forEach(it=>{
          let obj = {}
          obj = Object.assign(obj,it);
          obj.meterCode = this.meterList.filter(ele=>ele.id === obj.meterCode && ele.type==='d')[0].name
          obj.planCycle = this.dateTypeList.filter(ele=>ele.key === obj.planCycle)[0].value
          obj.status = this.statusOptions.filter(ele=>ele.id === obj.status)[0].name
          obj.patrolUserId = this.userList.filter(ele=>ele.userId === obj.patrolUserId)[0].username
          data.push(obj)
        })
        this.export2Excel(header,props,fileName,data)
      },
      export2Excel (tH, fi, fiNa, dataList) {
        var tHeader = tH
        var filterVal = fi
        var fileName = fiNa
        require.ensure([], () => {
          const {export_json_to_excel} = require('@/utils/Export2Excel.js')
          const list = JSON.parse(JSON.stringify(dataList));

          const data = this.formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, fileName)
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      }
    }
  }
</script>
